package cn.zspt.phonebook.service.imp;

import cn.zspt.phonebook.domain.PhoneBook;
import cn.zspt.phonebook.mapper.PhoneMapper;
import cn.zspt.phonebook.service.PhoneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PhoneServiceImpl implements PhoneService {
    @Autowired
    private PhoneMapper phoneMapper;
    public List<PhoneBook> findAllPhoneBook(){
        return phoneMapper.findAllPhoneBook();
    }

    @Override
    public List<PhoneBook> findPhoneBookByName(String keyword) {
        return phoneMapper.findPhoneBookByName(keyword);
    }

    @Override
    public void addPhoneBook(PhoneBook phoneBook) {
        phoneMapper.addPhoneBook(phoneBook);
    }

    @Override
    public Map<String, List<PhoneBook>> findAllPhoneBooksByGroup() {
        List<PhoneBook> phoneBooks = phoneMapper.findAllPhoneBook();
        Map<String,List<PhoneBook>> map = new LinkedHashMap<>();
        for (PhoneBook phoneBook : phoneBooks) {
            if(map.containsKey(phoneBook.getInit())){
                map.get(phoneBook.getInit()).add(phoneBook);
            }else {
                map.put(phoneBook.getInit(),new java.util.ArrayList<>());
                map.get(phoneBook.getInit()).add(phoneBook);
            }
        }
        return map;
    }

}
